package com.example.springboot.interceptor;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**在执行Controller的任务之前判断是否有Session信息
 如果有Session信息就往下执行，去调用Controller。
 如果没有Session就跳转到登录页面或返回错误代码
*/
public class SessionInterceptor implements HandlerInterceptor {

	private static final Logger logger = LoggerFactory.getLogger(SessionInterceptor.class);

  @Override
  public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

	  logger.debug(">>>SessionInterceptor>>>>>>>在请求处理之前进行调用（Controller方法调用之前）");
      HttpSession session=request.getSession();
      if(session.getAttribute("User")!=null){
          return true;// 只有返回true才会继续向下执行，返回false取消当前请求
      }
      //String url = "/login.html";
      //request.getRequestDispatcher(url).forward(request,response);
      
      logger.error(">>>SessionInterceptor>>>>>>>取消当前请求");
      
      response.setContentType("text/html");
      response.setCharacterEncoding("UTF-8");
      response.getWriter().println("未登陆，当前请求已取消！");
      return false;
  }

  @Override
  public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

	  logger.debug(">>>SessionInterceptor>>>>>>>请求处理之后进行调用，但是在视图被渲染之前（Controller方法调用之后）");
  }

  @Override
  public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

	  logger.debug(">>>SessionInterceptor>>>>>>>在整个请求结束之后被调用，也就是在DispatcherServlet 渲染了对应的视图之后执行（主要是用于进行资源清理工作）");
  }
  
}
